const path = require('path');
const fs = require('fs');
const jwt = require('jsonwebtoken');

const Jwt = module.exports = function (data) {
    if (!(this instanceof Jwt)) return new Jwt(data);
    this.data = data;
}

Jwt.prototype = {
    constructor: Jwt,
    createToken() {
        let data = this.data;
        let cert = fs.readFileSync(path.join(__dirname, '../pem/rsa_private_key.pem')); //私钥
        let token = jwt.sign({
            data,
            exp: Math.floor(Date.now() / 1000) + 1000 * 60 * 60 * 24 * 7, //过期时间为1周
        }, cert, {
            algorithm: 'RS256'
        })

        return token;
    },
    verifyToken() {
        let token = this.data;
        token = token.indexOf('Bearer') == 0 ? token.split(' ')[1] : token;
        let cert = fs.readFileSync(path.join(__dirname, '../pem/rsa_public_key.pem')); //公钥
        let res;
        try {
            let results = jwt.verify(token, cert, { //验证token
                algorithms: ['RS256']
            });
            let {
                exp = 0 //  解构得到有效期
            } = results,
            current = Math.floor(Date.now() / 1000); //当前时间

            if (current <= exp) { //有效期内可以拿到结果
                res = results.data || {};
            }

        } catch (error) {
            res = ''
        }
        return res;
    }
}